--[[ =========================================================================
   OPERATION ZENH -- attrape le fondateur, pour CC:Tweaked
   -------------------------------------------------------------------------
   A installer sur un ADVANCED COMPUTER avec :
     - un MONITEUR AVANCE tactile a cote (le terrain de jeu)
     - un Wired Modem (pour la banque)
     - client_solde.lua et login_term.lua sur le meme computer

   Le joueur se connecte sur le terminal du computer, paie sa partie, puis
   joue sur le moniteur : Zenh surgit des buissons puis traverse l'ecran en
   vol, on lui jette des Poke Balls en cliquant dessus.

   Pourquoi le login est sur le terminal : l'evenement monitor_touch de
   ComputerCraft ne dit pas QUI a clique. Impossible donc de crediter le
   bon compte si plusieurs personnes tapent l'ecran. Le terminal reserve
   le moniteur a un joueur pour toute la manche.

   PRIME : le bareme est calcule sur le rapport entre ton score et ta
   moyenne personnelle. Un jeu d'adresse ne peut pas avoir un RTP unique
   comme une roulette ; avec ce systeme, un debutant et un expert
   retrouvent des retours comparables (mesures : 1,14 et 0,89).
========================================================================= ]]

--------------------------------------------------------------------------
-- CONFIGURATION
--------------------------------------------------------------------------
local CFG = {
  duration   = 45,          -- duree d'une manche (secondes)
  balls      = 25,          -- stock de Poke Balls
  fps        = 12,
  betLevels  = { 10, 25, 50, 100, 250 },
  scoreFile  = "zenh_scores.dat",
  statsFile  = "zenh_stats.dat",
  topCount   = 10,
  refScore   = 2000,        -- moyenne supposee tant qu'on n'a pas d'historique

  -- bareme : rapport score / moyenne personnelle -> multiplicateur
  ladder = {
    { 1.45, 3.2 }, { 1.30, 2.6 }, { 1.15, 1.75 },
    { 1.00, 1.1 }, { 0.85, 0.55 }, { 0.70, 0.2 }, { 0.00, 0.0 },
  },

  points = { zenh = 100, gold = 500, comboStep = 20, comboCap = 5,
             voltorbe = -50, voltorbeCost = 2 },
  goldChance = 0.015,
}

--------------------------------------------------------------------------
-- PERIPHERIQUES
--------------------------------------------------------------------------
local bank  = dofile("client_solde.lua")
local login = dofile("login_term.lua")

local mon = peripheral.find("monitor")
if not mon then error("Aucun moniteur trouve (il doit etre avance/tactile).", 0) end

local speaker = peripheral.find("speaker")
local function beep(p, inst)
  if speaker then pcall(speaker.playNote, inst or "bit", 1, p or 12) end
end

--------------------------------------------------------------------------
-- PALETTE ET FRAMEBUFFER
--------------------------------------------------------------------------
local PAL = {
  ["0"] = 0xffffff, ["1"] = 0xff7a18, ["2"] = 0x2fa3f0, ["3"] = 0xa8dcff,
  ["4"] = 0xffd23f, ["5"] = 0x9dff5c, ["6"] = 0xff5fb0, ["7"] = 0x14141c,
  ["8"] = 0x3c3c4a, ["9"] = 0x1d7a3a, ["a"] = 0x8b5cd6, ["b"] = 0x2b4a7a,
  ["c"] = 0x6b4a20, ["d"] = 0x2fa84f, ["e"] = 0xd11f2a, ["f"] = 0x000000,
}

mon.setTextScale(0.5)
for hex, rgb in pairs(PAL) do
  pcall(mon.setPaletteColour, 2 ^ tonumber(hex, 16), rgb)
end

local W, H = mon.getSize()
local ct, cf, cb = {}, {}, {}

local function fbInit()
  W, H = mon.getSize()
  ct, cf, cb = {}, {}, {}
  for y = 1, H do ct[y], cf[y], cb[y] = {}, {}, {} end
end

local function clear(bg)
  bg = bg or "f"
  for y = 1, H do
    for x = 1, W do ct[y][x], cf[y][x], cb[y][x] = " ", "f", bg end
  end
end

local function px(x, y, bg)
  x, y = math.floor(x), math.floor(y)
  if x >= 1 and x <= W and y >= 1 and y <= H then
    ct[y][x], cf[y][x], cb[y][x] = " ", "f", bg
  end
end

local function rect(x1, y1, x2, y2, bg)
  x1, y1 = math.floor(x1), math.floor(y1)
  x2, y2 = math.floor(x2), math.floor(y2)
  for y = y1, y2 do for x = x1, x2 do px(x, y, bg) end end
end

local function text(x, y, s, fg, bg)
  x, y = math.floor(x), math.floor(y)
  for i = 1, #s do
    local xx = x + i - 1
    if xx >= 1 and xx <= W and y >= 1 and y <= H then
      ct[y][xx] = s:sub(i, i)
      cf[y][xx] = fg or "0"
      if bg then cb[y][xx] = bg end
    end
  end
end

local function center(x1, x2, y, s, fg, bg)
  x1, x2 = math.floor(x1), math.floor(x2)
  text(x1 + math.floor(((x2 - x1 + 1) - #s) / 2), y, s, fg, bg)
end

local function push()
  for y = 1, H do
    mon.setCursorPos(1, y)
    mon.blit(table.concat(ct[y]), table.concat(cf[y]), table.concat(cb[y]))
  end
end

fbInit()

--------------------------------------------------------------------------
-- FONTE 5x7
--------------------------------------------------------------------------
local FONT = {
  O="01110/10001/10001/10001/10001/10001/01110",
  P="11110/10001/10001/11110/10000/10000/10000",
  E="11111/10000/10000/11110/10000/10000/11111",
  R="11110/10001/10001/11110/10100/10010/10001",
  A="01110/10001/10001/11111/10001/10001/10001",
  T="11111/00100/00100/00100/00100/00100/00100",
  I="11111/00100/00100/00100/00100/00100/11111",
  N="10001/11001/10101/10011/10001/10001/10001",
  Z="11111/00001/00010/00100/01000/10000/11111",
  H="10001/10001/10001/11111/10001/10001/10001",
  G="01110/10001/10000/10111/10001/10001/01111",
  C="01110/10001/10000/10000/10000/10001/01110",
  S="01111/10000/10000/01110/00001/00001/11110",
  ["!"]="00100/00100/00100/00100/00100/00000/00100",
  ["0"]="01110/10011/10101/10101/11001/10001/01110",
  ["1"]="00100/01100/00100/00100/00100/00100/01110",
  ["2"]="01110/10001/00001/00110/01000/10000/11111",
  ["3"]="11111/00010/00100/00010/00001/10001/01110",
  ["4"]="00010/00110/01010/10010/11111/00010/00010",
  ["5"]="11111/10000/11110/00001/00001/10001/01110",
  ["6"]="00110/01000/10000/11110/10001/10001/01110",
  ["7"]="11111/00001/00010/00100/01000/01000/01000",
  ["8"]="01110/10001/10001/01110/10001/10001/01110",
  ["9"]="01110/10001/10001/01111/00001/00010/01100",
  [" "]="00000/00000/00000/00000/00000/00000/00000",
}
local GLYPH = {}
for ch, def in pairs(FONT) do
  local rows = {}
  for r in def:gmatch("[^/]+") do rows[#rows + 1] = r end
  GLYPH[ch] = rows
end

local function bigWidth(s, sx) sx = sx or 1; return #s * (5 * sx + sx) - sx end

local function bigText(x0, y0, s, colFn, sx, sy)
  sx, sy = sx or 1, sy or 1
  local cx = x0
  for i = 1, #s do
    local g = GLYPH[s:sub(i, i)] or GLYPH[" "]
    for ry = 1, 7 do
      for rx = 1, 5 do
        if g[ry]:sub(rx, rx) == "1" then
          for iy = 0, sy - 1 do
            for ix = 0, sx - 1 do
              px(cx + (rx - 1) * sx + ix, y0 + (ry - 1) * sy + iy,
                 colFn(cx + (rx - 1) * sx + ix, ry))
            end
          end
        end
      end
    end
    cx = cx + 5 * sx + sx
  end
end

--------------------------------------------------------------------------
-- SPRITES
--------------------------------------------------------------------------
-- Zenh : le fondateur. Corps blanc cerne de noir, deux yeux, un bec,
-- et son Z sur le ventre.
-- Zenh, releve pixel par pixel sur le logo du fondateur :
-- houppe fendue, deux yeux ronds, bec recourbe, large sourire,
-- et le Z en zigzag sur le ventre.
-- Zenh, releve sur le logo du fondateur : houppe fendue, deux yeux
-- ronds, bec recourbe, large sourire, et le Z en zigzag sur le ventre.
-- Le corps sort du cadre par le bas, comme sur l'original.
-- Zenh : sprite obtenu par conversion directe du logo du fondateur
-- (echantillonnage 30x18, une case de moniteur faisant 6x9 pixels,
-- soit 1,5 fois plus de colonnes que de lignes pour rester rond).
local ZENH = {
".........KKKKKKK.KKKKK........",
"........KKKKKKWWKWWWWKK.......",
"........KWWWWWWWWWWWWWK.......",
".......KWKKWWWWWWWWWKWWK......",
".......KWKKWWKKKWWWWKWWK......",
"......KWWWWWWWWWKWWWWWWWK.....",
"......KWWWWWWKKKKWWWWWWWK.....",
"....KKWKWWWWKWWWKWWWWWKWK.....",
"...KKWWWKKWWWKWWWKKKKKWWWK....",
"...KWWWWWWWWWKKWWKWWWWWWWWK...",
"..KWWWWWWWWWWWKKKWWWWWWWWWK...",
".KKWWWWWWKKKKWWWWWWWWWWWWWWK..",
".KWWWWWWWWWWWWKKKKKWWWWWWWWK..",
".KWWWWWWWWWWWWWWKKKWWWWWWWWK..",
"KKWWWWWWWWWWWKKKWWWWWWWWWWWK..",
"KKWWWWWWWWKKKWWWWWWWWWWWWWWK..",
".KWWWWWWWKKWWWWWWWWWWWWWWWK...",
".KWWWWWWWWWKKWWWWWWWWWWWWWK...",
}

local ZENH_W, ZENH_H = 30, 18

local VOLTORBE = {
  "..KKKKK..",
  ".KEEEEEK.",
  "KEWEEEWEK",
  "KWWWWWWWK",
  ".KKWWWKK.",
}

local MASTER = {
  "..KKKKK..",
  ".KAAAAAK.",
  "KA6AAA6AK",
  "KWWWWWWWK",
  ".KKWWWKK.",
}

local BALL = {
  ".KKK.",
  "KEEEK",
  "KKWKK",
  "KWWWK",
  ".KKK.",
}

local TAUNTS = {
  "Rate !",
  "Trop lent !",
  "C'est tout ?",
  "Je suis le patron ici.",
  "Meme pas peur.",
  "La Team Rocket recrute mal.",
}

local function drawSprite(art, x0, y0, map)
  x0, y0 = math.floor(x0), math.floor(y0)
  for ry, row in ipairs(art) do
    for rx = 1, #row do
      local ch = row:sub(rx, rx)
      if ch ~= "." then px(x0 + rx - 1, y0 + ry - 1, map[ch] or "0") end
    end
  end
end

local ZENH_MAP  = { K = "f", W = "0" }
local GOLD_MAP  = { K = "f", W = "4" }
local VOLT_MAP  = { K = "f", E = "e", W = "0" }
local MAST_MAP  = { K = "f", A = "a", ["6"] = "6", W = "0" }
local BALL_MAP  = { K = "f", E = "e", W = "0" }

--------------------------------------------------------------------------
-- SCORES ET STATISTIQUES
--------------------------------------------------------------------------
local function loadTable(file)
  if not fs.exists(file) then return {} end
  local f = fs.open(file, "r")
  local data = textutils.unserialize(f.readAll() or "")
  f.close()
  return (type(data) == "table") and data or {}
end

local function saveTable(file, data)
  local f = fs.open(file, "w")
  f.write(textutils.serialize(data))
  f.close()
end

local topScores = loadTable(CFG.scoreFile)   -- { {player=, score=} ... }
local stats = loadTable(CFG.statsFile)       -- stats[player] = {games=, total=}

local function playerAverage(player)
  local s = stats[player]
  if not s or (s.games or 0) < 3 then
    -- pas encore d'historique : on melange avec la reference
    local g = s and s.games or 0
    local t = s and s.total or 0
    return (t + CFG.refScore * (3 - g)) / 3
  end
  return s.total / s.games
end

local function recordGame(player, score)
  local s = stats[player] or { games = 0, total = 0, best = 0 }
  s.games = s.games + 1
  s.total = s.total + score
  s.best = math.max(s.best or 0, score)
  stats[player] = s
  saveTable(CFG.statsFile, stats)

  topScores[#topScores + 1] = { player = player, score = score }
  table.sort(topScores, function(a, b) return a.score > b.score end)
  while #topScores > CFG.topCount do table.remove(topScores) end
  saveTable(CFG.scoreFile, topScores)
end

local function multiplierFor(score, average)
  local ratio = score / math.max(1, average)
  for _, e in ipairs(CFG.ladder) do
    if ratio >= e[1] then return e[2], ratio end
  end
  return 0, ratio
end

--------------------------------------------------------------------------
-- ETAT PARTAGE
--------------------------------------------------------------------------
local STATE = { playing = false, player = nil }

--------------------------------------------------------------------------
-- DECOR
--------------------------------------------------------------------------
local L = {}
local function layout()
  fbInit()
  L.x1, L.y1, L.x2, L.y2 = 2, 2, W - 1, H - 1
  L.hudH = 2
  L.fieldY1 = L.y1 + L.hudH
  L.fieldY2 = L.y2 - 4          -- 4 lignes de buissons en bas
  L.groundY = L.fieldY2 + 1
  -- trous / buissons ou Zenh se planque
  L.holes = {}
  local n = math.max(3, math.min(6, math.floor((L.x2 - L.x1) / (ZENH_W + 6))))
  for i = 1, n do
    L.holes[i] = {
      x = L.x1 + math.floor((i - 0.5) * (L.x2 - L.x1 + 1) / n)
          - math.floor(ZENH_W / 2),
      y = L.groundY - 2,
    }
  end
end
layout()

local CHASE = { "4", "1", "e", "c" }
local function drawFrame(t, flash)
  local step = math.floor(t * 6)
  for x = 1, W do
    local a = flash and (((x + step * 2) % 4 < 2) and "0" or "4")
              or CHASE[((x + step) % 4) + 1]
    px(x, 1, a); px(x, H, a)
  end
  for y = 1, H do
    local a = flash and (((y + step * 2) % 4 < 2) and "0" or "4")
              or CHASE[((y + step) % 4) + 1]
    px(1, y, a); px(W, y, a)
  end
end

-- ballon Miaouss de la Team Rocket, il derive au fond du decor
local BALLOON = {
  "...KKKKKK...",
  "..KWWWWWWK..",
  ".KW4WWWW4WK.",
  ".KWWWKKWWWK.",
  ".KWWKWWKWWK.",
  "..KWWWWWWK..",
  "...KKKKKK...",
  "....K..K....",
  "...KKKKKK...",
  "...KeeeeK...",
  "...KKKKKK...",
}
local BALLOON_MAP = { K = "f", W = "4", ["4"] = "1", e = "e" }

local function drawScene(t)
  local horizon = L.groundY - 4

  -- ciel en degrade : plus clair pres de l'horizon
  rect(L.x1, L.fieldY1, L.x2, L.fieldY2, "2")
  for y = horizon - 5, L.fieldY2 do
    if y >= L.fieldY1 then
      for x = L.x1, L.x2 do px(x, y, "3") end
    end
  end

  -- nuages sur deux plans, vitesses differentes
  for i = 1, 5 do
    local speed = (i % 2 == 0) and 1.6 or 0.7
    local cx = L.x1 + ((i * 41 + math.floor(t * speed)) % (L.x2 - L.x1 - 8))
    local cy = L.fieldY1 + 1 + (i % 3)
    rect(cx, cy, cx + 6, cy, "0")
    rect(cx + 1, cy - 1, cx + 5, cy - 1, "0")
    rect(cx + 2, cy + 1, cx + 4, cy + 1, "0")
  end

  -- ballon Miaouss, tres lent, au loin
  local bx = L.x1 + ((math.floor(t * 2.5)) % (L.x2 - L.x1 + 24)) - 12
  local by = L.fieldY1 + 2 + math.floor(math.sin(t * 0.7) * 1.5)
  drawSprite(BALLOON, bx, by, BALLOON_MAP)

  -- montagnes lointaines
  for x = L.x1, L.x2 do
    local u = (x - L.x1)
    local hgt = 3 + math.floor(2.2 * math.abs(math.sin(u * 0.11))
                + 1.6 * math.abs(math.sin(u * 0.047 + 1.3)))
    for y = horizon - hgt, horizon - 1 do px(x, y, "b") end
    if hgt >= 5 then px(x, horizon - hgt, "0") end   -- neige au sommet
  end

  -- ligne d'arbres
  for x = L.x1, L.x2, 5 do
    local hgt = 2 + ((x * 7) % 2)
    for k = 0, hgt do
      local wdt = math.max(0, hgt - k)
      for dx = -wdt, wdt do px(x + dx, horizon + k - hgt, "9") end
    end
    px(x, horizon, "c")
  end

  -- sol et hautes herbes
  rect(L.x1, L.groundY, L.x2, L.y2, "d")
  for x = L.x1, L.x2 do
    if (x * 13) % 5 < 2 then px(x, L.groundY, "9") end
    if (x * 7) % 9 == 0 then px(x, L.groundY - 1, "9") end
  end

  -- buissons ou Zenh se planque
  for _, h in ipairs(L.holes) do
    rect(h.x, h.y + 1, h.x + ZENH_W - 1, h.y + 3, "d")
    rect(h.x + 2, h.y, h.x + ZENH_W - 3, h.y + 1, "d")
    for dx = 0, ZENH_W - 1, 3 do px(h.x + dx, h.y, "9") end
    rect(h.x + 5, h.y + 2, h.x + ZENH_W - 6, h.y + 3, "9")
  end
end

--------------------------------------------------------------------------
-- LA PARTIE
--------------------------------------------------------------------------
local function newTarget(kind, mode, t)
  local tgt = { kind = kind, mode = mode, born = t }
  if mode == "hole" then
    local h = L.holes[math.random(#L.holes)]
    tgt.x, tgt.y = h.x, h.y - ZENH_H + 3
    tgt.life = 1.5
  else
    local dir = (math.random() < 0.5) and 1 or -1
    tgt.x = (dir == 1) and (L.x1 - ZENH_W) or (L.x2 + 1)
    tgt.y = L.fieldY1 + 2 + math.random(0, math.max(0, L.fieldY2 - L.fieldY1 - ZENH_H - 3))
    tgt.vx = dir * (18 + math.random() * 14)
    tgt.phase = math.random() * 6.28
    tgt.life = 99
  end
  if kind == "voltorbe" or kind == "master" then
    tgt.w, tgt.h = 9, 5
  else
    tgt.w, tgt.h = ZENH_W, ZENH_H
  end
  return tgt
end

local function drawTarget(tgt, t)
  local map, art
  if tgt.kind == "zenh" then art, map = ZENH, ZENH_MAP
  elseif tgt.kind == "gold" then art, map = ZENH, GOLD_MAP
  elseif tgt.kind == "voltorbe" then art, map = VOLTORBE, VOLT_MAP
  else art, map = MASTER, MAST_MAP end
  drawSprite(art, tgt.x, tgt.y, map)
  if tgt.kind == "gold" then
    -- il scintille
    if math.floor(t * 8) % 2 == 0 then
      px(tgt.x - 1, tgt.y - 1, "0")
      px(tgt.x + tgt.w, tgt.y + 2, "0")
    end
  end
end

local function playGame(player, bet)
  STATE.playing = true
  local t0 = os.clock()
  local balls = CFG.balls
  local score, combo, caught = 0, 0, 0
  local targets, effects = {}, {}
  local nextSpawn = t0 + 0.8
  local spawned = 0
  local goldSeen = false
  local taunt, tauntUntil = nil, 0

  -- compte a rebours
  for i = 3, 1, -1 do
    clear("f")
    drawScene(os.clock())
    local w = bigWidth(tostring(i), 3)
    bigText(math.floor((W - w) / 2), math.floor(H / 2) - 10, tostring(i),
            function() return "4" end, 3, 3)
    center(L.x1, L.x2, math.floor(H / 2) + 12, "PRET ?", "0")
    drawFrame(os.clock())
    push()
    beep(10)
    sleep(0.7)
  end

  local timer = os.startTimer(1 / CFG.fps)
  local last = os.clock()

  while true do
    local ev, p1, p2, p3 = os.pullEvent()
    local now = os.clock()
    local elapsed = now - t0

    if ev == "monitor_touch" and balls > 0 then
      balls = balls - 1
      local hit = nil
      for i, tgt in ipairs(targets) do
        if p2 >= tgt.x and p2 <= tgt.x + tgt.w - 1
           and p3 >= tgt.y and p3 <= tgt.y + tgt.h - 1 then
          hit = i
          break
        end
      end

      if hit then
        local tgt = table.remove(targets, hit)
        if tgt.kind == "voltorbe" then
          score = score + CFG.points.voltorbe
          balls = math.max(0, balls - CFG.points.voltorbeCost)
          combo = 0
          effects[#effects + 1] = { kind = "boom", x = tgt.x + 4,
                                    y = tgt.y + 2, born = now }
          beep(3, "bass")
        elseif tgt.kind == "master" then
          effects[#effects + 1] = { kind = "text", x = tgt.x, y = tgt.y,
                                    born = now, msg = "MASTER BALL !", col = "a" }
          balls = balls + 5
          beep(20, "bell")
        else
          combo = math.min(CFG.points.comboCap, combo + 1)
          local pts = ((tgt.kind == "gold") and CFG.points.gold
                       or CFG.points.zenh) + combo * CFG.points.comboStep
          score = score + pts
          caught = caught + 1
          if tgt.kind == "gold" then goldSeen = true end
          effects[#effects + 1] = { kind = "catch", x = tgt.x, y = tgt.y,
                                    born = now, pts = pts,
                                    gold = (tgt.kind == "gold") }
          beep(14 + combo, "bell")
        end
      else
        combo = 0
        effects[#effects + 1] = { kind = "miss", x = p2, y = p3, born = now }
        taunt = TAUNTS[math.random(#TAUNTS)]
        tauntUntil = now + 1.2
        beep(5)
      end

    elseif ev == "timer" and p1 == timer then
      local dt = now - last
      last = now
      timer = os.startTimer(1 / CFG.fps)

      -- vagues : buissons, puis vol, puis melange
      local wave = (elapsed < CFG.duration / 3) and "hole"
                   or ((elapsed < 2 * CFG.duration / 3) and "fly")
                   or ((math.random() < 0.5) and "hole" or "fly")

      -- apparitions, de plus en plus rapides
      if now >= nextSpawn and elapsed < CFG.duration - 1 then
        local kind = "zenh"
        local r = math.random()
        if r < CFG.goldChance then kind = "gold"
        elseif r < 0.20 then kind = "voltorbe"
        elseif r < 0.25 then kind = "master" end
        targets[#targets + 1] = newTarget(kind, wave, now)
        spawned = spawned + 1
        local ramp = 1 - (elapsed / CFG.duration) * 0.45
        nextSpawn = now + (1.5 + math.random() * 0.8) * ramp
      end

      -- deplacement et expiration
      for i = #targets, 1, -1 do
        local tgt = targets[i]
        if tgt.mode == "fly" then
          tgt.x = tgt.x + tgt.vx * dt
          tgt.y = tgt.y + math.sin((now - tgt.born) * 3 + tgt.phase) * 6 * dt
          if tgt.x < L.x1 - tgt.w - 2 or tgt.x > L.x2 + 2 then
            table.remove(targets, i)
          end
        else
          local life = tgt.life * (1 - (elapsed / CFG.duration) * 0.4)
          if now - tgt.born > life then table.remove(targets, i) end
        end
      end

      -- rendu
      clear("f")
      drawScene(now)
      for _, tgt in ipairs(targets) do drawTarget(tgt, now) end

      -- effets
      for i = #effects, 1, -1 do
        local e = effects[i]
        local age = now - e.born
        if age > 1.1 then
          table.remove(effects, i)
        elseif e.kind == "catch" then
          -- la balle tremble trois fois puis se referme dans un eclat
          local wob = (age < 0.7) and math.floor(math.sin(age * 18) * 2) or 0
          local bx = e.x + math.floor(ZENH_W / 2) - 2
          drawSprite(BALL, bx + wob, e.y + 6, BALL_MAP)
          if age > 0.7 then
            local r = (age - 0.7) * 26
            for a = 0, 11 do
              local ang = a * math.pi / 6
              px(bx + 2 + math.cos(ang) * r * 1.6,
                 e.y + 8 + math.sin(ang) * r,
                 (a % 2 == 0) and "4" or "0")
            end
            center(e.x - 4, e.x + ZENH_W + 4, e.y + 3,
                   e.gold and "JACKPOT !" or "GOTCHA !",
                   e.gold and "4" or "0")
            center(e.x - 4, e.x + ZENH_W + 4, e.y + 4, "+" .. e.pts,
                   e.gold and "4" or "5")
          end
        elseif e.kind == "miss" then
          local r = age * 12
          for a = 0, 7 do
            local ang = a * math.pi / 4
            px(e.x + math.cos(ang) * r * 1.6, e.y + math.sin(ang) * r, "0")
          end
        elseif e.kind == "boom" then
          local r = age * 16
          for yy = -4, 4 do
            for xx = -8, 8 do
              local d = math.sqrt((xx / 1.7) ^ 2 + yy * yy)
              if math.abs(d - r) < 1.2 then px(e.x + xx, e.y + yy, "4")
              elseif math.abs(d - r) < 2.2 then px(e.x + xx, e.y + yy, "e") end
            end
          end
        elseif e.kind == "text" then
          center(e.x - 8, e.x + 16, e.y, e.msg, e.col)
        end
      end

      -- HUD : bandeau noir, score au centre, Poke Balls a droite
      rect(L.x1, L.y1, L.x2, L.y1 + 1, "f")
      text(L.x1, L.y1, player, "4", "f")

      local sc = "SCORE " .. score
      center(L.x1, L.x2, L.y1, sc, "0", "f")

      -- une Poke Ball par balle restante, jusqu'a 12, puis un compteur
      local shown = math.min(balls, 12)
      local bx0 = L.x2 - shown * 2 + 1
      for i = 1, shown do
        local bx = bx0 + (i - 1) * 2
        px(bx, L.y1, "e")
        px(bx, L.y1 + 1, "0")
      end
      if balls > 12 then
        local extra = "+" .. (balls - 12)
        text(bx0 - #extra - 1, L.y1, extra, "0", "f")
      elseif balls <= 5 then
        local warn = "PLUS QUE " .. balls
        text(bx0 - #warn - 2, L.y1, warn,
             (math.floor(now * 4) % 2 == 0) and "e" or "4", "f")
      end

      if combo > 1 then
        local ct = "COMBO x" .. combo
        text(L.x1, L.y1 + 1, ct, "6", "f")
      end

      -- jauge de temps
      local frac = math.max(0, 1 - elapsed / CFG.duration)
      local gw = math.floor((L.x2 - L.x1 + 1) * frac)
      local gy = L.y1 + 1
      for x = L.x1 + 12, L.x2 do px(x, gy, "8") end
      for x = L.x1 + 12, L.x1 + 11 + math.max(0, gw - 12) do
        px(x, gy, (frac < 0.2) and "e" or "5")
      end

      if taunt and now < tauntUntil then
        center(L.x1, L.x2, L.fieldY1 + 1, taunt, "0")
      end

      drawFrame(now, goldSeen and (elapsed % 1 < 0.5))
      push()

      if elapsed >= CFG.duration or balls <= 0 then break end
    end
  end

  STATE.playing = false
  return score, caught, goldSeen
end

--------------------------------------------------------------------------
-- ECRANS DU MONITEUR
--------------------------------------------------------------------------
local function drawResultScreen(player, score, gain, mult, ratio, record)
  clear("f")
  drawScene(os.clock())
  rect(L.x1, L.fieldY1, L.x2, L.fieldY2, "7")

  local w = bigWidth("SCORE", 1)
  bigText(math.floor((W - w) / 2), L.fieldY1 + 2, "SCORE",
          function() return "4" end)
  local s = tostring(score)
  local sw = bigWidth(s, 2)
  bigText(math.floor((W - sw) / 2), L.fieldY1 + 11, s,
          function(_, gy) return gy <= 3 and "0" or "3" end, 2, 2)

  center(L.x1, L.x2, L.fieldY1 + 27,
         "PRIME x" .. mult .. "   ->   " .. gain .. " credits",
         gain > 0 and "5" or "e")
  center(L.x1, L.x2, L.fieldY1 + 29,
         "ta moyenne : " .. math.floor(ratio * 100) .. "% de ton niveau", "8")
  if record then
    center(L.x1, L.x2, L.fieldY1 + 31, "NOUVEAU RECORD PERSONNEL !", "4")
  end
  drawFrame(os.clock(), true)
  push()
end

local function attractFrame(t)
  clear("f")
  drawScene(t)

  -- Zenh se promene et nargue les passants
  local u = (t * 0.12) % 1
  local zx = L.x1 + (L.x2 - L.x1 - ZENH_W) * (0.5 + 0.5 * math.sin(t * 0.6))
  local zy = L.groundY - ZENH_H - 1 + math.floor(math.abs(math.sin(t * 3)) * -2)
  drawSprite(ZENH, zx, zy, ZENH_MAP)

  local msg = TAUNTS[(math.floor(t / 3.5) % #TAUNTS) + 1]
  local bw = #msg + 2
  local bx = math.min(L.x2 - bw, math.floor(zx) + ZENH_W + 2)
  rect(bx, zy, bx + bw - 1, zy + 2, "0")
  text(bx + 1, zy + 1, msg, "f", "0")

  -- titre
  local title = "OPERATION ZENH"
  local sc = (bigWidth(title, 2) <= (L.x2 - L.x1 - 2)) and 2 or 1
  local w = bigWidth(title, sc)
  local sweep = (t * 26) % (w + 60) - 30
  bigText(math.floor((W - w) / 2) + 1, L.fieldY1 + 2, title,
          function() return "f" end, sc, sc)
  bigText(math.floor((W - w) / 2), L.fieldY1 + 1, title, function(x, gy)
    local d = x - math.floor((W - w) / 2) - sweep
    if d > -2 and d < 2 then return "0" end
    if gy <= 3 then return "4" else return "e" end
  end, sc, sc)

  center(L.x1, L.x2, L.fieldY1 + 2 + 7 * sc,
         "AVIS DE RECHERCHE - TEAM ROCKET", "e")
  center(L.x1, L.x2, L.fieldY1 + 4 + 7 * sc,
         "Inscris-toi sur le terminal a cote", "0")

  -- tableau des scores
  local ty = L.fieldY1 + 7 + 7 * sc
  if ty + 4 < L.fieldY2 then
    center(L.x1, L.x2, ty, "MEILLEURES PRISES", "4")
    for i = 1, math.min(#topScores, math.max(0, L.fieldY2 - ty - 1)) do
      local e = topScores[i]
      local line = string.format("%2d. %-16s %6d", i, e.player, e.score)
      center(L.x1, L.x2, ty + i, line, (i == 1) and "4" or "0")
    end
    if #topScores == 0 then
      center(L.x1, L.x2, ty + 1, "aucune prise enregistree", "8")
    end
  end

  drawFrame(t)
  push()
end

local function attractLoop()
  while true do
    if not STATE.playing then attractFrame(os.clock()) end
    sleep(1 / 6)
  end
end

--------------------------------------------------------------------------
-- TERMINAL
--------------------------------------------------------------------------
local TW, TH = term.getSize()

local function tFill(y, bg)
  term.setBackgroundColor(bg)
  term.setCursorPos(1, y)
  term.write(string.rep(" ", TW))
end

local function tLabel(x, y, s, fg, bg)
  term.setCursorPos(x, y)
  term.setTextColor(fg)
  term.setBackgroundColor(bg or colors.black)
  term.write(s)
end

local function tCenter(y, s, fg, bg)
  tLabel(math.floor((TW - #s) / 2) + 1, y, s, fg, bg)
end

local function terminalSplash()
  term.setBackgroundColor(colors.black)
  term.clear()
  tFill(1, colors.red)
  tCenter(1, "OPERATION ZENH", colors.yellow, colors.red)
  tCenter(3, "Mission Team Rocket", colors.white)
  tCenter(5, "Attrape le fondateur a coups de Poke Balls", colors.lightGray)
  tCenter(6, CFG.duration .. " secondes, " .. CFG.balls .. " balles", colors.lightGray)
  tCenter(8, "Attention aux Voltorbes !", colors.orange)
  if #topScores > 0 then
    tCenter(10, "RECORD : " .. topScores[1].player .. "  " ..
            topScores[1].score, colors.yellow)
  end
  tCenter(TH - 2, "Une touche pour t'inscrire", colors.yellow)
  while true do
    local ev = os.pullEvent()
    if ev == "key" or ev == "mouse_click" then return end
  end
end

local function chooseBet(player, credit)
  local idx = 2
  local buttons
  local function draw(msg, msgCol)
    buttons = {}
    term.setBackgroundColor(colors.black)
    term.clear()
    tFill(1, colors.red)
    tLabel(2, 1, "OPERATION ZENH", colors.yellow, colors.red)
    local right = player .. "  " .. credit
    tLabel(TW - #right, 1, right, colors.white, colors.red)

    local avg = playerAverage(player)
    tCenter(3, "Ta moyenne : " .. math.floor(avg) .. " points", colors.lightGray)
    tCenter(4, "La prime se calcule sur ton propre niveau", colors.gray)

    tLabel(2, 6, "MISE", colors.lightGray)
    term.setBackgroundColor(colors.red)
    term.setCursorPos(8, 6); term.write(" - ")
    buttons[#buttons + 1] = { id = "-", x1 = 8, x2 = 10, y = 6 }
    term.setBackgroundColor(colors.green)
    term.setCursorPos(20, 6); term.write(" + ")
    buttons[#buttons + 1] = { id = "+", x1 = 20, x2 = 22, y = 6 }
    tLabel(13, 6, tostring(CFG.betLevels[idx]), colors.yellow)

    term.setBackgroundColor(colors.green)
    term.setCursorPos(2, 9); term.write(string.rep(" ", 22))
    tLabel(6, 9, "LANCER LA PARTIE", colors.white, colors.green)
    buttons[#buttons + 1] = { id = "go", x1 = 2, x2 = 23, y = 9 }

    term.setBackgroundColor(colors.red)
    term.setCursorPos(TW - 11, 9); term.write(string.rep(" ", 10))
    tLabel(TW - 9, 9, "QUITTER", colors.white, colors.red)
    buttons[#buttons + 1] = { id = "quit", x1 = TW - 11, x2 = TW - 2, y = 9 }

    tCenter(12, "Le jeu se joue sur le moniteur", colors.lightGray)
    tFill(TH, colors.gray)
    if msg then tCenter(TH, msg, msgCol or colors.white, colors.gray) end
  end

  draw("Espace pour lancer, +/- pour la mise")
  while true do
    local ev, p1, p2, p3 = os.pullEvent()
    local action
    if ev == "mouse_click" then
      for _, b in ipairs(buttons) do
        if p3 == b.y and p2 >= b.x1 and p2 <= b.x2 then action = b.id end
      end
    elseif ev == "key" then
      if p1 == keys.q then action = "quit"
      elseif p1 == keys.space or p1 == keys.enter then action = "go"
      elseif p1 == keys.equals or p1 == keys.numPadAdd then action = "+"
      elseif p1 == keys.minus or p1 == keys.numPadSubtract then action = "-"
      end
    end
    if action == "quit" then return nil
    elseif action == "+" then idx = math.min(idx + 1, #CFG.betLevels); draw()
    elseif action == "-" then idx = math.max(idx - 1, 1); draw()
    elseif action == "go" then return CFG.betLevels[idx] end
  end
end

--------------------------------------------------------------------------
-- BOUCLE PRINCIPALE
--------------------------------------------------------------------------
local function mainLoop()
  while true do
    terminalSplash()
    local player = login.authenticate("Connexion Operation Zenh")
    if player then
      local credit = bank.getBalance(player)
      local bet = chooseBet(player, credit)
      if bet then
        local newBal, err = bank.addBalance(player, -bet)
        if not newBal then
          term.setBackgroundColor(colors.black)
          term.clear()
          tCenter(math.floor(TH / 2), err or "Banque injoignable", colors.red)
          sleep(2)
        else
          STATE.player = player
          term.setBackgroundColor(colors.black)
          term.clear()
          tCenter(math.floor(TH / 2) - 1, "PARTIE EN COURS", colors.yellow)
          tCenter(math.floor(TH / 2) + 1, "Regarde le moniteur !", colors.white)

          local average = playerAverage(player)
          local previousBest = (stats[player] and stats[player].best) or 0
          local score = playGame(player, bet)
          local mult, ratio = multiplierFor(score, average)
          local gain = math.floor(bet * mult)
          if gain > 0 then bank.addBalance(player, gain) end
          recordGame(player, score)

          drawResultScreen(player, score, gain, mult, ratio,
                           score > previousBest)

          term.setBackgroundColor(colors.black)
          term.clear()
          tFill(1, colors.red)
          tCenter(1, "RESULTAT", colors.yellow, colors.red)
          tCenter(4, "Score : " .. score, colors.white)
          tCenter(6, "Prime x" .. mult .. "  ->  " .. gain .. " credits",
                  gain > 0 and colors.lime or colors.red)
          tCenter(8, "Credit : " .. bank.getBalance(player), colors.yellow)
          tCenter(TH - 2, "Une touche pour continuer", colors.lightGray)
          os.pullEvent("key")
          STATE.player = nil
          sleep(0.2)
        end
      end
    end
  end
end

math.randomseed((os.epoch and os.epoch("utc") or os.time()) % 2147483647)

local ok, err = pcall(function()
  parallel.waitForAny(mainLoop, attractLoop)
end)

term.setBackgroundColor(colors.black)
term.setTextColor(colors.white)
term.clear()
term.setCursorPos(1, 1)
mon.setBackgroundColour(colours.black)
mon.clear()
if not ok and err ~= "Terminated" then error(err, 0) end
print("Operation Zenh : arret.")